package com.tedu._03vehicle.base.exception;

import com.tedu._03vehicle.base.response.JsonResult;
import com.tedu._03vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleIllArgumentException(IllegalArgumentException ex){
        String data =ex.getMessage();
        log.error("IllegalArgumentException:"+data);
        return JsonResult.fail(data);
    }
    //@ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data =ex.getMessage();
        log.error("RuntimeException:"+data);
        return JsonResult.fail(data);
    }
    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String message = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:"+message);
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }
    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException ex){
        String message = ex.getMessage().split(":")[1].trim();
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }
    //@ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex){
        String data =ex.getMessage();
        log.error("Throwable:"+data);
        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
    }
}
